package com.zbc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zbc.constant.MessageConstant;
import com.zbc.dto.UserLoginDTO;
import com.zbc.entity.User;
import com.zbc.exception.LoginFailedException;
import com.zbc.mapper.UserMapper;
import com.zbc.properties.WecharProperties;
import com.zbc.service.UserService;
import com.zbc.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WecharProperties wecharProperties;

    @Autowired
    private UserMapper userMapper;

    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) throws IOException {
        String openid = getOpenid(userLoginDTO.getCode());

        if(openid == null && openid.equals("")){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        User user= userMapper.getUserByOpenId(openid);
        if(user==null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.addUser(user);
        }
        return user;
    }

    public String getOpenid(String code) throws IOException {
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("appid", wecharProperties.getAppid());
        paramMap.put("secret", wecharProperties.getSecret());
        paramMap.put("js_code",code);
        paramMap.put("grant_type", "authorization_code");

        String result = HttpClientUtil.doGet(WX_LOGIN,paramMap);

        JSONObject jsonObject = JSONObject.parseObject(result);
        String openid = jsonObject.getString("openid");

        return openid;
    }
}
